<template>
  <div>
    <el-input v-model="roleName" disabled size="mini"></el-input>
    <el-tree
      :data="assignList"
      show-checkbox
      node-key="id"
      ref="tree"
      highlight-current
      :props="defaultProps"
      default-expand-all
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
    >
    </el-tree>
    <el-button type="primary" size="small" @click="save">保存</el-button>
    <el-button size="small" @click="$router.push({path:'/acl/role/list'})">取消</el-button>
  </div>
</template>

<script>
export default {
  name: "RoleAuth",
  data() {
    return {
      roleId: "",
      roleName: "",
      assignList: [],
      defaultProps: {
        label: "name",
        children: "children",
      },
      roleIdaAssignList: [], //权限id
      loading: false,
    };
  },
  mounted() {
    this.roleId = this.$route.params.id;
    this.roleName = this.$route.query.roleName;
    this.getRoleAssign();
    this.getRoleIdAssign();
  },
  methods: {
    //获取所有的权限列表
    async getRoleAssign() {
      try {
        this.loading = true;
        let res = await this.$API.permission.getPermissionList(this.roleId);
        this.assignList = res.data.children;
        this.loading = false;
      } catch (error) {
        this.loading = false;
        this.$message.error(error.message);
      }
    },
    //获取当前id下的角色所有的权限列表
    async getRoleIdAssign() {
      try {
        let res = await this.$API.permission.toAssign(this.roleId);
        const roleIdaAssignList = res.data.children;
        this.roleIdaAssignList = roleIdaAssignList;
        const checkedIds = this.getCheckedId(roleIdaAssignList);
        this.$refs.tree.setCheckedKeys(checkedIds);
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    getCheckedId(auth, init = []) {
      return auth.reduce((pre, next) => {
        if (next.select && next.level === 4) {
          pre.push(next.id);
        } else if (next.children) {
          this.getCheckedId(next.children, init);
        }
        return pre;
      }, init);
    },
    async save() {
      var ids = this.$refs.tree.getCheckedKeys().join(',');
      try {
        this.$API.permission.doAssign(this.roleId,ids);
        this.$message.success('权限修改成功');
        this.getRoleIdAssign()
      } catch (error) {
        
      }
    },
  },
};
</script>

<style lang="scss" scoped>
</style>